package org.biogroovy.mindmaps

import org.biogroovy.models.Omim

public class OMIM2mindmap{


	/**
	 * This method writes the Omim record out as a mind map file.
	 * @param omim The omim record.
	 * @param out  The output stream.
	 */
	public void writeFile(Omim omim, OutputStream out) throws IOException{

		// GPath definitions
			def main_text = omim.'Mim-entry'.'Mim-entry_text'.'Mim-text'.'Mim-text_text'.text()
		def symbolList = omim.'Mim-entry'.'Mim-entry_symbol'.text().split(","); 
		def pmidList =  omim.getMedlineLinks()
		def textFieldList = omim.getTextElements();
		def nucList = omim.getNucleotideLinks()
		def protList = omim.getProteinLinks();
		def refList = omim.getReferences();

		// URL definitions
		def entrezgeneUrl = "";
		def pubmedUrl = "http://www.ncbi.nlm.nih.gov/sites/entrez?holding=&amp;db=pubmed&amp;cmd=search&amp;term="
		def omimUrl = "http://www.ncbi.nlm.nih.gov/entrez/dispomim.cgi?id="
		def nucUrl = "http://www.ncbi.nlm.nih.gov/nucleotide/"
		def protUrl = "http://www.ncbi.nlm.nih.gov/protein/"


		out << '<?xml version="1.0"?>\n'
		out << '<map>\n'
		out <<  "<node text=\"${omim.title}\" link='${omimUrl}${omim.mimId}'>\n"

		// handle description
		out << "<richcontent type=\"note\"><html><head/><body>${main_text}</body></html></richcontent>"

		// handle Gene Symbol Nodes
		out << '<node text="genes" position=\"left\">'
		symbolList.each(){

			out << "<node text=\"${it.trim()}\" link='http://www.ncbi.nlm.nih.gov/sites/entrez?holding=&amp;db=gene&amp;cmd=search&amp;term=${it}%20AND%20Homo%20Sapiens[organism]'/>"
	}
	out << '</node>'
	
	// handle references
	out << '<node text="References" folded="true">'
	refList.each(){node ->
		def citTitle = node.'Mim-reference_citationTitle'.text();
		def uid = node.'Mim-reference_pubmedUID'.text()
	
		out << "<node text=\"${citTitle}\" link=\"${pubmedUrl}${uid}\"/>"
	}
	out << '</node>'
	
	// handle TEXT nodes
	textFieldList.each(){
		def reftitle = it.'Mim-text_label'.text();
		def text = it.'Mim-text_text'.text()
		out << "<node text=\"${reftitle}\" folded=\"true\">"
	
	 out << "<richcontent type=\"note\"><html><head/><body><![CDATA[${text}]]></body></html></richcontent>"
	
		def uids = it.'Mim-text_neighbors'.'Mim-link'.'Mim-link_uids'.text().split(",")
	
		uids.each(){pmid ->
			if (pmid != ""){
			out << "<node text=\"${pmid}\" link=\"${pubmedUrl}${pmid}\"/>"
			}
		}
	
		out << "</node>"
	}
	
	// handle nucleotide links
	out << "<node text=\"Nucleotides\" position=\"left\">"
	nucList.each(){
		out << "<node text=\"${it}\" link=\"${nucUrl}${it}\"/>"
	}
	
	out << "</node>"
	
	// handle protein links
	out << "<node text=\"Proteins\" position=\"left\">"
	protList.each(){
		out << "<node text=\"${it}\" link=\"${protUrl}${it}\"/>"
	}
	
	out << "</node>";
	out << '</node></map>'
	out.flush();
	out.close();
	}
    
}



